<?php

namespace App\Models\Basic;

use App\Helpers\Code;
use App\Models\BaseModel;
use Illuminate\Support\Facades\Auth;

class RegionProvince extends BaseModel
{

    protected $table = 'provinces';
    protected $fillable = [
        'region_id', 'title', 'code', 'description', 'rank', 'state', 'charged_by', 'created_by', 'updated_by', 'data_scope'
    ];
    public $sorters = ['rank'];
    public $params = ['title', 'code', 'region'];

    public function chargedBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'charged_by');
    }

    public function region()
    {
        return $this->belongsTo('App\Models\Basic\Region', 'region_id');
    }

    /**
     * 添加省区
     * @param $data
     * @return int
     */
    public function addRegionProvince($data)
    {
        $title = $this->where('title', $data['title'])->where('region_id', $data['region_id'])->count();
        if ($title > 0) {
            return Code::INSIDE_ERROR;
        }

        $userId = Auth::id();
        $data['created_by'] = $userId;
        $data['updated_by'] = $userId;
        $data['data_scope'] = $this->getDataScope();

        return $this->create($data);
    }

    /**
     * 编辑省区
     * @param $data
     * @param $id
     * @return int|null
     */
    public function editRegionProvince($data, $id)
    {
        $model = $this->find($id);

        if (!$model) {
            return null;
        }

        //判断名称是否重复
        $title = $this->where('title', $data['title'])->where('region_id', $data['region_id'])->where('id', '!=', $id)->count();
        if ($title > 0) {
            return Code::INSIDE_ERROR;
        }

        $data['updated_by'] = Auth::id();

        return $model->updateOrCreate(['id' => $id], $data);

    }

    /**
     * 省区列表
     * @param $limit
     * @param $sorter
     * @param $search
     * @param $defaultSorter
     * @return mixed
     */
    public function getRegionProvinceList($limit, $sorter, $search, $defaultSorter)
    {
        $perPage = $limit > 0 ? $limit : $this->limit;
        if (!isset($defaultSorter)) {
            $model = $this->orderBy('created_at', 'desc');
        } else {
            $model = $this->orderBy($sorter[0], $sorter[1]);
        }

        $model->select(['id', 'region_id', 'title', 'code', 'description', 'rank', 'state', 'charged_by', 'created_at'])
            ->with(['chargedBy:id,username', 'region:id,title']);

        foreach ($search as $key => $value) {
            switch ($key) {
                case 'code':
                case 'title':
                    $model->where($key, 'like', '%' . $value . '%');
                    break;
                case 'region':
                    $model->whereHas('region', function($region) use ($value) {
                        $region->where('title', $value);
                    });
                    break;
            }
        }

        return $model->paginate($perPage)->toArray();
    }
}
